<template>
  <div class="section">
    <el-card>
      <div slot="header">
        <div>当前课程：{{ course.courseName }}</div>
      </div>
      <div>
        <el-tree
          v-loading="isLoading"
          :data="treeData"
          node-key="id"
          :props="defaultProps"
          draggable
          :expand-on-click-node="false"
          :allow-drop="allowDrop"
          @node-drop="handleNodeDrop"
        >
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span>{{ node.label }}</span>
            <span>
              <template v-if="data.sectionName">
                <el-button size="mini" @click="editSection(data)"
                  >编辑</el-button
                >
                <el-button
                  type="primary"
                  size="mini"
                  @click="addLesson(data, node)"
                >
                  添加课时
                </el-button>
              </template>
              <template v-else>
                <el-button size="mini" @click="editLesson(data, node)">
                  编辑
                </el-button>
                <el-button
                  type="success"
                  size="mini"
                  @click="
                    $router.push({
                      name: 'edit-lesson',
                      params: {
                        id: data.id,
                        courseName: course.courseName,
                        theme: data.theme
                      }
                    })
                  "
                >
                  上传视频
                </el-button>
              </template>
              <el-button size="mini" @click="dialogVisible = true">
                {{ getState(data.status) }}
              </el-button>
            </span>
          </span>
        </el-tree>
      </div>
    </el-card>
    <el-dialog
      title="章节信息"
      :visible.sync="dialogSectionVisible"
      width="40%"
      @close="resetSection"
    >
      <add-or-edit-section
        @sectionSuccess="onSectionSuccess"
        @sectionCancel="resetSection"
        :is-edit="isSectionEdit"
        :course-name="courseName"
        :section-id="sectionId"
      ></add-or-edit-section>
    </el-dialog>
    <el-dialog
      title="课时信息"
      :visible.sync="dialogLessonVisible"
      width="40%"
      @close="resetLesson"
    >
      <add-or-edit-lesson
        @lessonSuccess="onLessonSuccess"
        @lessonCancel="resetLesson"
        v-bind="{
          isEdit: isLessonEdit,
          courseName: courseName,
          lessonId: lessonId,
          sectionId: sectionId,
          courseId: id,
          sectionName: sectionName
        }"
      ></add-or-edit-lesson>
    </el-dialog>
  </div>
</template>

<script>
import { getCourseById, getSectionAndLesson } from '@/service/course'
import { saveOrUpdateSection, saveOrUpdateLesson } from '@/service/lesson'
import addOrEditSection from './components/add-or-edit-section.vue'
import addOrEditLesson from './components/add-or-edit-lesson.vue'
export default {
  components: { addOrEditSection, addOrEditLesson },
  name: 'Section',
  props: {
    id: {
      type: [Number, String]
    }
  },
  data () {
    return {
      courseName: '',
      sectionName: '',
      // 章节id
      sectionId: '',
      // 课时id
      lessonId: '',
      isSectionEdit: false,
      isLessonEdit: false,
      dialogVisible: false,
      dialogLessonVisible: false,
      dialogSectionVisible: false,
      isLoading: false,
      course: {},
      treeData: [],
      options: [
        {
          status: 0,
          title: '已隐藏'
        },
        {
          status: 1,
          title: '待更新'
        },
        {
          status: 2,
          title: '已更新'
        }
      ],
      defaultProps: {
        label: data => {
          return data.sectionName || data.theme
        },
        children: 'lessonDTOS'
      }
    }
  },
  created () {
    this.loadCourse()
    this.loadSectionAndLesson()
  },
  methods: {
    // 编辑章节
    editSection (data) {
      this.courseName = this.course.courseName
      this.sectionId = data.id
      this.isSectionEdit = true
      this.dialogSectionVisible = true
    },
    // 重置章节编辑信息
    resetSection () {
      this.isSectionEdit = false
      this.sectionId = ''
      this.courseName = ''
      this.dialogSectionVisible = false
    },
    onSectionSuccess () {
      this.resetSection()
      this.loadSectionAndLesson()
    },
    // onSectionCancel () {
    //   this.isSectionEdit = false
    //   this.sectionId = ''
    // },
    // 重置课时编辑信息
    resetLesson () {
      this.isLessonEdit = false
      this.lessonId = ''
      this.sectionId = ''
      this.courseName = ''
      this.sectionName = ''
      this.dialogLessonVisible = false
    },
    // 新增课时
    addLesson (data, node) {
      console.log(data, node)
      this.sectionId = data.id
      this.sectionName = data.sectionName
      this.courseName = this.course.courseName
      this.dialogLessonVisible = true
    },
    // 编辑课时
    editLesson (data, node) {
      this.courseName = this.course.courseName
      this.lessonId = data.id
      this.sectionName = node.parent.data.sectionName
      this.isLessonEdit = true
      this.dialogLessonVisible = true
      // console.log(data, node)
    },
    onLessonSuccess () {
      this.resetLesson()
      this.loadSectionAndLesson()
    },
    // onLessonCancel () {},
    // 获取课程章节/课时状态对应值
    getState (status) {
      const statusMap = ['已隐藏', '待更新', '已更新']
      return statusMap[status]
    },
    // 加载课程信息
    async loadCourse () {
      const { data } = await getCourseById({
        courseId: this.id
      })
      if (data.code === '000000') {
        this.course = data.data
      }
    },
    // 加载课程章节和课时
    async loadSectionAndLesson () {
      this.isLoading = true
      const { data } = await getSectionAndLesson({
        courseId: this.id
      })
      if (data.code === '000000') {
        this.treeData = data.data
      }
      this.isLoading = false
    },
    // 判断是否可拖曳插入
    // 规则1：章节不可被插入其他章节 type !== 'innner'
    // 规则2：课时父章节sectionId相同可拖曳
    allowDrop (draggingNode, dropNode, type) {
      // console.log(draggingNode, dropNode, type)
      // console.log(draggingNode.data.sectionId, dropNode.data.sectionId)
      if (
        type !== 'inner' &&
        draggingNode.data.sectionId === dropNode.data.sectionId
      ) {
        return true
      }
      return false
      // if(draggingNode)
    },
    // 处理节点拖曳结束后章节/课时的顺序更新
    async handleNodeDrop (draggingNode, dropNode) {
      this.isLoading = true
      const message = draggingNode.data.sectionId
        ? '课时顺序更新'
        : '章节顺序更新'
      try {
        // await Promise.all(

        // )
        const temp = dropNode.parent.childNodes.map((m, i) => {
          // 判断是章节还是课时
          // 有sectionId 是课时
          if (draggingNode.data.sectionId) {
            return saveOrUpdateLesson({
              id: m.data.id,
              orderNum: i
            })
          } else {
            return saveOrUpdateSection({
              id: m.data.id,
              orderNum: i
            })
          }
        })
        await Promise.all(temp)
        this.$message.success(message + '成功')
      } catch (error) {
        console.log(error)
        this.$message.error(message + '失败', error)
      }
      this.isLoading = false
    }
  }
}
</script>

<style lang="scss" scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
::v-deep .el-tree-node__content {
  height: 50px;
}
::v-deep .custom-tree-node {
  height: 100%;
  border-bottom: 2px solid #f8f8f8;
}
</style>
